/**
Application: This is the main file list panel
Author: chilei
Date:2012/12/3
*/
Ext.namespace("Ext.clNameSpace");

Ext.clNameSpace.filePagePanel = function(config){

	 // create the Data Store
    var store = new Ext.data.Store({
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.ScriptTagProxy({
            url: 'login/dopathlist.action'
        }),

        // create reader that reads the Topic records
        reader: new Ext.data.JsonReader({
            root: 'filelist',
            totalProperty: 'totalCount',
            id: 'filelistid',
            fields: [
                'title', 'version', 'type','size',
                'contributor','uploadtime',
                'downloadtimes','describe',
                {name:'download'}
                //{name: 'lastpost', mapping: 'lastpost', type: 'date', dateFormat: 'timestamp'},                
            ]
        })
    });
    //store.setDefaultSort('lastpost', 'desc');
     // pluggable renders
     /*
    function renderTopic(value, p, record){
        return String.format(
                '<b><a href="http://extjs.com/forum/showthread.php?t={2}" target="_blank">{0}</a></b><a href="http://extjs.com/forum/forumdisplay.php?f={3}" target="_blank">{1} Forum</a>',
                value, record.data.forumtitle, record.id, record.data.forumid);
    }
    function renderLast(value, p, r){
        return String.format('{0}<br/>by {1}', value.dateFormat('M j, Y, g:i a'), r.data['lastposter']);
    }
    function ddd(filevalue){
    	var a = filevalue;
    	alert(a);
    }
    */
    function renderTopic(value,p,record){
    	if(record.data.version == null || record.data.version == ""){
    		return "<img src='img/forums/forum.gif'/>"+value;
    	}
    	else{
    		return value;
    	}
    	
    }
    function downloadbtn(h,g,e,j,f){
    	var filevalue = e.data.title;
        var ver = e.data.version;
        if(ver == null || ver == "")
        	return "";
        else        
        	return "<span style='cursor:'><input type='button' onclick='downloadFile()' style='cursor:pointer' value='下载'></span>";
    }
    
    
	var cm = new Ext.grid.ColumnModel(
		[new Ext.grid.CheckboxSelectionModel({
		singleSelect : false
		}),{
           id: 'title', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "文件标题",
           dataIndex: 'title',
           width:170,
           renderer: renderTopic
        },{
           id:'version',
           header:'版本',
           dataIndex:'version',          
           width:50,
           renderer:function(h,g,e,j,f){
           		var thisver = e.data.version;
           		if(thisver > 1){
           			return '<img src="./img/forums/messages.png"></img>';
           		}
           		else{
           			return '<img src="./img/forums/message.png"></img>';
           		}
           }
        },{
           header: "类型",
           width:50,
            
           dataIndex: 'type'
        },{
           header: "大小",
           dataIndex: 'size',
           width: 50
        },{
           id: 'contributor',
           header: "文件上传者",
           dataIndex: 'contributor',
           width: 100
         
        },{
           id:'uploadtime',
           header:'上传时间',
           dataIndex:'uploadtime',
           width:70
           
        },{
           id:'downloadtimes',
           header:'下载次数',
           dataIndex:'downloadtimes',
           width:70
        },{
           id:'describe',
           header:'文件描述',
           dataIndex:'describe',
           width:140
        },{
           header:'下载',
           width:50,
           dataIndex:'download',
           renderer:downloadbtn
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;
	

    // trigger the data store load
    store.load({params:{start:0, limit:20}});
	var _config = Ext.apply({
		width:800,
		height:500,
		baseCls:'x-plain',
		frame:true,
		id:'filepage_panel',
		store:store,
		cm:cm,
		trackMouseOver:false,
		
		sm:new Ext.grid.CheckboxSelectionModel ({singleSelect : false}),
		loadMask:{msg:'loading...'},
		ViewConfig:{
			forceFit:false,
			enableRowBody:true,
			showPreview:true,
			getRowClass:function(record, rowIndex, p, store){
                if(this.showPreview){
                    p.body = '<p>'+record.data.excerpt+'</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
		},
		listeners:{
			"celldblclick":function(g,r,c,e){
				var record = g.store.getAt(r);
				var val = record.get("title");
				var version = record.get("version");
				
				if(version == null || version == ""){
					if(val != "...返回上级目录"){
						var items = Ext.getCmp("main_content").items;
						
				       	if(items != null){
				       	for (var i = 0; i < items.getCount(); i=i+1)   
				              Ext.getCmp("main_content").remove(items.get(i)); 
				       	}
				       	var clfl = new Ext.clNameSpace.fileListPanel({
				    	});
				        Ext.getCmp("main_content").add(clfl);	 
				        var _panel = Ext.getCmp("file_path");	  
				    	Ext.apply(_panel,{html:"<font size=1>"+curpath+">"+val+"</font>"});
				    	var tmpcur = curpath.replace(">","\\");    
				    	
				    	var curr = tmpcur+"\\"+val;
				    	curpath = curpath+">"+val;
						Ext.Ajax.request({
				    	    	url:"login/docurrentpath.action",
				    	    	params:{
				    	    		currentPath:curr
				    	    	},
				    	    	success:function(response,options){
				    	    		Ext.getCmp("filepage_panel").store.reload();
				    	    		clfl.show();
				    	    		Ext.getCmp("main_content").doLayout();
				    	    	}
				    	});	
					}
					if(val == "...返回上级目录"){
						var items = Ext.getCmp("main_content").items;
						
				       	if(items != null){
				       	for (var i = 0; i < items.getCount(); i=i+1)   
				              Ext.getCmp("main_content").remove(items.get(i)); 
				       	}
				       	var clfl = new Ext.clNameSpace.fileListPanel({
				    	});
				        Ext.getCmp("main_content").add(clfl);
				        var lastindex = curpath.lastIndexOf(">");	
				        curpath = curpath.substring(0,lastindex); 
				        var _panel = Ext.getCmp("file_path");	 
				    	Ext.apply(_panel,{html:"<font size=1>"+curpath+"</font>"});
				    	var tmpcur = curpath.replace(">","\\");        	
				    	var curr = tmpcur;
						Ext.Ajax.request({
				    	    	url:"login/docurrentpath.action",
				    	    	params:{
				    	    		currentPath:curr
				    	    	},
				    	    	success:function(response,options){
				    	    		Ext.getCmp("filepage_panel").store.reload();
				    	    		clfl.show();
				    	    		Ext.getCmp("main_content").doLayout();
				    	    	}
				    	});	
					}
				}
			}
		},
		bbar:new Ext.PagingToolbar({
			id:'filelistbbar',
			pageSize: 20,
            store: store,
            displayInfo: true,
            displayMsg: '文件 {0} - {1} of {2}',
            emptyMsg: "没有文件了",
            items:[
                '-', {
                pressed: true,
                enableToggle:true,
                text: '预览',
                handler:function(){
                	var grid = Ext.getCmp("filepage_panel");
    				if(grid.getSelectionModel().hasSelection()){
    					var records = grid.getSelectionModel().getSelections();
    					var filelist = new Array();
    					for(var i = 0; i < records.length; i++){
    						filelist[i] = records[i].data.title;
    						var ver = records[i].data.type;
    						var filename = filelist[i];
    						
    						var s = /jpg|bmp|gif|png|jpeg$/
    						if(s.test(ver)){
    							Ext.Ajax.request({
    								url:'login/showpic.action',
    								params:{
    									picname:filelist[i]
    								},
    								success:function(response,options){
    									var jpgWin = new Ext.Window({
    										title:'图片',
    										items:{		
    											html:'<img src = "./flexpaper/tmp.jpg"></img>'
    										}
    									});
    									jpgWin.show();
    								}
    							});
    							
    							   							
    						}
    						else if(filelist[i] != "...返回上级目录"){
    								Ext.Msg.alert("文件转换需要较长时间，请耐心等待");
	        						Ext.Ajax.request({
	        						url:'login/preview.action',
	        						params:{
	        							filename:filelist[i]
	        						},
	        						success:function(response,options){
	        							Ext.Msg.alert("转换成功");
	        							window.open("common/preview.html?filename="+encodeURI(encodeURI(filelist[i])));
	        							
	        						},
	        						failure:function(response,options){
	        							Ext.Msg.alert("转换失败");
	        						}
	        						});   									
    							}
    						}
    				}else{
    					Ext.Msg.alert("请选择");
    				}
                }
            }]			
		})
	},config);
	Ext.clNameSpace.filePagePanel.superclass.constructor.call(this,_config);
	
};
Ext.extend(Ext.clNameSpace.filePagePanel,Ext.grid.GridPanel,{});

//mainpanel
Ext.clNameSpace.fileListPanel = function(config){
	var up_panel = new Ext.Panel({
		id:'file_path',
		border:false
	});
	
	
	var search_panel = new Ext.Panel({
		border:false,
		id:'search_panel',
		layout:"table",
		width:800,
		layoutConfig:{
			columns:3
		},	
		items:[
			{xtype:'label',text:'  ',height:20,width:400},
			{xtype:'textfield',fieldLabel:'搜索条件',name:'innersearchfile',id:'innersearchfile',width:200,listeners:{
				"specialkey":function(field,e){
					 if (e.getKey() == Ext.EventObject.ENTER) {
	                        var searchname = Ext.getCmp("innersearchfile").getValue();
							var filter = /^[#$&\*]+/
							if(filter.test(searchname)){
								alert("含有非法字符");
								return;
							}
							content_panel.getStore().proxy.url = "login/searchcurfile.action?searchname="+encodeURI(encodeURI(searchname));
							content_panel.getStore().reload();
                     }
				}
			}},
			{xtype:'button',text:'搜索',pressed:true,id:'innersearch',listeners:{
				"click":function(){
					var searchname = Ext.getCmp("innersearchfile").getValue();
					var filter = /^[#$&\*]+/
					if(filter.test(searchname)){
						alert("含有非法字符");
						return;
					}
					content_panel.getStore().proxy.url = "login/searchcurfile.action?searchname="+encodeURI(encodeURI(searchname));
					content_panel.getStore().reload();
				}
			}}
		]
	});
	var content_panel = new Ext.clNameSpace.filePagePanel();	
	
	var content_toolbar = new Ext.Toolbar(
	{
								width:810,
								baseCls:'x-plain',
								frame:true,
                        		items:[/*new Ext.Toolbar.Button({
                        		baseCls:'x-plain',
								frame:true,
                        		text:'下载',
                        		
                        		handler:function(){
                        			var grid = Ext.getCmp("filepage_panel");
    								if(grid.getSelectionModel().hasSelection()){
    									var records = grid.getSelectionModel().getSelections();
    									var filelist = new Array();
    									for(var i = 0; i < records.length; i++){
    										filelist[i] = records[i].data.title;
    			
    										if(filelist[i] != "...返回上级目录"){
    											window.open('login/download.action?filename='+encodeURI(encodeURI(filelist[i])),'_self');
    										}
    				
    									}
    								}else{
    									Ext.Msg.alert("请选择");
    								}
                        		}
                        		}),'-',*/{
                        		baseCls:'x-plain',
								frame:true,
                        		text:'上传',
                        		width:200,
                        		handler:function(){
                        			var uploadP = new Ext.clNameSpace.uploadWin({
                        			});
                        			uploadP.show();
                        		}
                        		},'-',{
                        		baseCls:'x-plain',
								frame:true,
                        		text:'上传新版本',
                        		handler:function(){
                        			var grid = Ext.getCmp("filepage_panel");
    								if(grid.getSelectionModel().hasSelection()){
    									var uploadP = new Ext.clNameSpace.uploadnewWin({
                        				
                        				});
                        				uploadP.show();
    								}else{
    									Ext.Msg.alert("请选择");
    								}
                        			
                        		}
                        		},'-',{
                        		baseCls:'x-plain',
								frame:true,
                        		text:'删除文件',
                        		xtype:'button',
                        		width:200,
                        		handler:function(){
                        			Ext.MessageBox.show({title:'删除提示',msg:'确定删除么？',buttons:Ext.Msg.YESNO,fn:function(id){
	                        			if(id=="no")
	                        				return;
	                        			if(id == "cancel")
	                        				return;
	                        			var grid = Ext.getCmp("filepage_panel");
	    								if(grid.getSelectionModel().hasSelection()){
	    									var records = grid.getSelectionModel().getSelections();
	    									var filelist = new Array();
	    									for(var i = 0; i < records.length; i++){
	    										filelist[i] = records[i].data.title;
	    										Ext.Ajax.request({
	    											url:'login/delfile.action',
	    											params:{
	    												filelist:filelist
	    											},
	    											success:function(response,options){
	    												Ext.Msg.alert("删除成功!");
	    												Ext.getCmp("filepage_panel").store.reload();
	    											}
	    										});
	    										
	    				
	    									}
	    								}else{
	    									Ext.Msg.alert("请选择");
	    								}
	    							}});
                        		}
                        		},'-',new Ext.Toolbar.Button({
                        			cls:'x-btn-text-icon',
	                        		text:'新建文件夹',
	                        		icon:'./img/forums/forum.gif',
	                        		handler:function(){
	                        			//传递当前路径
	                        			var namewin = new Ext.Window({
	                        				width:200,
	                        				height:100,
	                        				title:'请输入文件夹名字',
	                        				items:[
	                        				{xtype:'textfield',id:'dirname',fieldLabel:'文件夹名字'}
	                        				],
	                        				buttons:[
												{text:'确定',type:'submit',id:'sb',height:100,handler:function(){
													
													Ext.Ajax.request({
														url:'login/createdir.action',
														params:{
															dirname:Ext.getCmp('dirname').getValue()
														},
														success:function(response,options){
															Ext.getCmp("forum-tree").root.reload();
															Ext.getCmp("filepage_panel").store.reload();
															namewin.close();
														}
													});
												}},
												{text:'取消',height:100,handler:function(){
													namewin.close();
												}}	
	                        				]
	                        			});
	                        			namewin.show();
	                        		}
                        		}),'-',{
                        			cls:'x-btn-text-icon',
									frame:true,
	                        		text:'删除文件夹',
	                        		icon:'./img/forums/forum.gif',
	                        		handler:function(){
	                        			Ext.MessageBox.show({title:'删除提示',msg:'确定删除么？',buttons:Ext.Msg.YESNO,fn:function(id){
	                        				if(id == "no")
	                        					return;
		                        			var grid = Ext.getCmp("filepage_panel");
		    								if(grid.getSelectionModel().hasSelection()){
		    									var records = grid.getSelectionModel().getSelections();
		    									var filelist = new Array();
		    									for(var i = 0; i < records.length; i++){
		    										filelist[i] = records[i].data.title;
		    										var dirversion = records[i].data.version;
		    										if(filelist[i] != "...返回上级目录"){
		    											
		    											if(dirversion == "" || dirversion == null){
		    												Ext.Ajax.request({
		    													url:'login/deldir.action',
		    													params:{
		    														dirname:filelist[i]
		    													},
		    													success:function(response,options){
																	Ext.Msg.alert('删除成功');
																	Ext.getCmp("forum-tree").root.reload();
																	Ext.getCmp("filepage_panel").store.reload();										
																}
		    												});
		    											}
		    										}
		    												
		    									}
		    								}else{
		    									Ext.Msg.alert("请选择");
		    								}
		    								}});
	                        		}
                        		}                   		
                        		]
                        	});
    
	var _config = Ext.apply({
		id:'flist',
		layout:'form',
		width:810,
		
		frame:true,
		baseCls:'x-plain',
		items:[up_panel,search_panel,content_toolbar,content_panel]
	},config);
	Ext.clNameSpace.fileListPanel.superclass.constructor.call(this,_config);
	
};
Ext.extend(Ext.clNameSpace.fileListPanel,Ext.Panel,{});
var cnt = 5;
function getchecktitle(){
    		var grid = Ext.getCmp("filepage_panel");
    		if(grid.getSelectionModel().hasSelection()){
    			var records = grid.getSelectionModel().getSelections();
    			var filelist = new Array();
    			for(var i = 0; i < records.length; i++){
    				filelist[i] = records[i].data.title;
    				if(filelist[i] != "...返回上级目录"){
    					//alert(encodeURI(encodeURI(filelist[i])));
    					//alert(encodeURI(encodeURI(filelist[i])));
    					window.open('login/download.action?filename='+encodeURI(encodeURI(filelist[i])),'_self');
    					var newtimes = 1+Number(records[i].data.downloadtimes);
    					records[i].set("downloadtimes",newtimes);
    					records[i].commit();
    				}
    			}
    		}else{
    			Ext.Msg.alert("请选择");
    		}
}
